package com.example.taobao

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import kotlinx.android.synthetic.main.fragment_mine.*
import kotlinx.android.synthetic.main.fragment_wei_tao.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import kotlin.concurrent.thread

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [FragmentWeiTao.newInstance] factory method to
 * create an instance of this fragment.
 */
class FragmentWeiTao : Fragment() {

    var search= "search"

    var weitaoList = ArrayList<weitaoData>()
    private var myAdapter: weitaoAdapter? = null
    private var myLayoutManager: LinearLayoutManager? = null

    val handle = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            weitaoList = msg.obj as ArrayList<weitaoData>
            myLayoutManager = LinearLayoutManager(context)
            myweitao.layoutManager = myLayoutManager
            myAdapter = context?.let { weitaoAdapter(it, weitaoList) }
            myweitao.adapter = myAdapter
            myAdapter?.setOnItemClickListener(object : weitaoAdapter.OnItemClickListener {
                override fun onItemClick(view: View, position: Int, type: Int) {
                    if (type == 1) {
                        val ins = Intent(context, MainDetails::class.java)
                        ins.putExtra("id", weitaoList[position].ids)
                        startActivity(ins)
                    }
                }
            })
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_wei_tao,container,false)
        return view
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initweitao()
        searchs.setOnClickListener {
            val ins = Intent(context, SearchedActivity::class.java)
            startActivity(ins)
        }

        goto_yh.setOnClickListener {
            val ins = Intent(context, Fragment_mine::class.java)
            startActivity(ins)
        }
    }

    private fun initweitao()
    {

        val us = "http://192.168.43.140:8080/aaa_war_exploded/forWeiTao.jsp"
        thread {
            var url = URL(us)
            //var url = URL("https://www.baidu.com")
            val connection = url.openConnection() as HttpURLConnection
            try {
                val response = StringBuilder()
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.requestMethod = "POST"

                connection.setRequestProperty("Accept-Charset", "UTF-8" )
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input) )


                var nums = 0
                var username = ""
                var desc = ""
                var fans = 0
                var content = ""
                var p1 = ""
                var p2 = ""
                var p3 = ""
                var readnum = 0
                var dznum = 0
                var id = 0

                var i = 0

                var meg : ArrayList<weitaoData> = ArrayList<weitaoData>()

                reader.use {
                    reader.forEachLine {
                        if(it.length > 0) {
                            if( i == 0)
                                nums = it.toInt()
                            else if( i == 1)
                                username = it
                            else if ( i == 2)
                                desc = it
                            else if( i == 3)
                                fans = it.toInt()
                            else if(i == 4)
                                content = it
                            else if( i == 5)
                                p1 = it
                            else if( i == 6)
                                p2 = it
                            else if( i == 7)
                                p3 = it
                            else if( i == 8)
                                readnum = it.toInt()
                            else if( i == 9)
                                dznum = it.toInt()
                            else if( i == 10) {
                                id = it.toInt()
                                Log.d(search, content)
                                meg.add(weitaoData(nums, username, desc, fans, p1, p2, p3, readnum, dznum, content, id) )
                                i = -1
                            }

                            i++
                        }
                    }
                }

                weitaoList = meg
                val msg = Message()
                msg.obj = meg
                handle.sendMessage(msg)


                //  showResponse(response.toString() )
            } catch (e: Exception )
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }

    }

    }
